<!-- 材料类别编辑弹窗 -->
<template>
  <div class="ele-body">
    <a-card :title="materialCategoryModalApp.title" :bordered="false">
      <a-form
        ref="form2"
        :model="materialCategoryModalApp.materialCategory"
        :rules="materialCategoryModalApp.rules"
        :label-col="{md: {span: 5}, sm: {span: 24}}"
        :wrapper-col="{md: {span: 19}, sm: {span: 24}}">
        <a-row :gutter="16">
          <a-col :lg="24" :md="12" :sm="24" :xs="24">
            <a-form-item label="名称:" name="name">
              <a-input
                v-model:value="materialCategoryModalApp.materialCategory.name"
                placeholder="请输入材料类别名称"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>

          <a-col :lg="24" :md="12" :sm="24" :xs="24">
            <a-form-item label="备注:" name="name">
              <a-textarea
                :auto-size="{ maxRows: 1 }"
                v-model:value="materialCategoryModalApp.materialCategory.remark"
                placeholder="请输入备注"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>

          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
              <!--class="ele-pull-right"-->
              <div v-if="materialCategoryModalApp.display">
                <teleport to="#materialCategoryEditModalFooter">
                  <div>
                    <a-space size="middle">
                      <a-button @click="materialCategoryListApp.editModalShowing=false">取消
                      </a-button>
                      <a-button
                        type="primary"
                        @click="onSubmit(materialCategoryModalApp.materialCategory)"
                        :loading="loading">提交
                      </a-button>
                      <!--<a-button v-if="!eid"
                                type="dashed"
                                @click="continueSubmit"
                                :loading="loading">继续提交
                      </a-button>-->
                    </a-space>
                  </div>
                </teleport>
              </div>
              <div v-if="!materialCategoryModalApp.display">
                <a-space size="middle">
                  <a-button @click="onBack()">返回列表</a-button>
                  <a-button
                    type="primary"
                    @click="onSubmit(materialCategoryModalApp.materialCategory)"
                    :loading="loading">提交
                  </a-button>
                  <!--<a-button v-if="!eid"
                            type="dashed"
                            @click="continueSubmit"
                            :loading="loading">继续提交
                  </a-button>-->
                </a-space>
              </div>

            </a-form-item>
          </a-col>
        </a-row>
<!--        <vxe-grid
          id="materialTable"
          ref="materialTable"
          v-bind="tableConfig"
          :edit-rules="tableConfig.editRules"
          :data="materialList"
        >
          <template #component_title>
        <span style="color: black;font-size: 15px;font-weight: bolder !important;">
          <i class="fa fa-pencil-square-o" aria-hidden="true">&nbsp;
          </i>材料管理</span>
          </template>
          <template #tool_button>
            <vxe-button
              title="新增账户"
              style="padding-top: 3px;padding-left: 7px;margin-right:10px "
              icon="fa fa-plus"
              name="新增账户"
              @click="insertEvent(-1)"
              circle v-if="!isDetail">
            </vxe-button>
          </template>

          &lt;!&ndash;          <template #status="{row}">
                      <div v-if="isDetail">
                        <a-tag v-if="row.status==='启用'" color="green">{{ row.status }}</a-tag>
              <a-tag v-if="row.status==='停用'" color="red">{{ row.status }}</a-tag>
            </div>
            <div v-else>
              <vxe-button type="button"
                          status="danger"
                          style="height: 28px;padding-bottom: 3px;"
                          v-if="row.status==='停用'"
                          @click="changeStatus(row)">停用
              </vxe-button>
              <vxe-button type="button"
                          status="success"
                          style="height: 28px;padding-bottom: 3px;"
                          v-if="row.status==='启用'"
                          @click="changeStatus(row)">启用
              </vxe-button>
            </div>
          </template>&ndash;&gt;

          <template #operate="{ row }">
            <a-space>
              <a-popconfirm
                title="确定要删除此账户吗？"
                @confirm="removeEvent(row)">
                <vxe-button icon="fa fa-trash" title="删除" circle></vxe-button>
              </a-popconfirm>
            </a-space>
          </template>
        </vxe-grid>-->

      </a-form>
    </a-card>

  </div>

</template>

<script>
import {defineComponent, inject, reactive, onMounted, ref} from 'vue'
import {useRoute,useRouter} from "vue-router"
import {MaterialCategoryService} from "@/views/restaurant/material/materialCategory/materialCategoryService";
import {VXETable} from 'vxe-table'
import {useStore} from "vuex";
import regions from 'ele-admin-pro/packages/regions.js';

export default defineComponent({
  components: {},
  setup(props) {
    console.log(props.editId)
    // 省市区数据
    const cityData = regions
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    let routeId = route.params.id;
    let materialCategoryListApp = inject('materialCategoryListApp', reactive({}));
    let materialCategoryGrid = inject('materialCategoryGrid',reactive({}))
    const materialCategoryModalApp = reactive({
      id: null,
      materialCategory: {},
      isEdit: false,
      display: false,
      rules: {}
    });
    // materialCategoryModalApp.rules = {};
    const materialEntityData = reactive({
      name: '',
      remark: ''
    })
    const materialTable = ref({})
    var materialMap = reactive({});
    let materialList = ref([]);
    const tableConfig = {
      border: true,
      showHeaderOverflow: true,
      showOverflow: true,
      resizeable: true,
      keepSource: true,
      highlightHoverRow: true,
      align: "center",

      columns: [
        {
          field: 'name',
          title: '材料名称',
          minWidth: "20%",
          fixed: "left",
          editRender: {name: 'input', attrs: {type: 'text'}, placeholder: '请点击输入材料名称'},

        },
        {
          field: 'remark',
          title: '备注',
          minWidth: "80%",
          editRender: {name: 'input', attrs: {type: 'text'}, placeholder: '请点击输入备注'},
        }
      ],

      keyboardConfig: {
        isArrow: true,
        isDel: true,
        isEnter: true,
        isTab: true,
        isEdit: true,
        /*editMethod({row, column}) {
          const $table = materialTable.value
          materialMap[row.bankAccount] = undefined

          // 重写默认的覆盖式，改为追加式
          if (row.status !== "停用" && !isDetail.value) {
            $table.setActiveCell(row, column)
          }
        }*/

      },

      //表格编辑设置
      editConfig: {
        trigger: 'dblclick',
        mode: 'cell',
        showStatus: true,
        icon: "fa fa-edit",
        showIcon: true,
        /*activeMethod({row}) {
          accountMap[row.bankAccount] = undefined
          return row.status !== "停用" && !isDetail.value;
        }*/
      },
      mouseConfig: {
        selected: true
      },
      //todo :表格内容注释设置

      tooltipConfig: {
        showAll: true,
        enterable: true,
      },

      //todo 工具栏
      toolbarConfig: {
        className: 'vxe-toolbar-mt',
        slots: {buttons: 'component_title', tools: 'tool_button'},
        refresh: false,
        import: false,
        export: false,
        print: false,
        zoom: true,
        custom: false
      },

      editRules: {
        name: [
          {
            required: true,
            type: "string",
            message: '账户名称必须输入',
            trigger: 'onSubmit',
            // trigger: "onSubmit"
          },
        ],
      },


    }
    const materials = reactive({})

    onMounted(() => {
      //清理数据
      materialCategoryModalApp.materialCategory = reactive({});
      if (routeId) {//路由
        materialCategoryModalApp.id = routeId;
        materialCategoryModalApp.display = false;
        findMaterialCategory(materialCategoryModalApp.id);
      } else if (materialCategoryListApp.editModalForEdit) {//修改弹窗
        materialCategoryModalApp.id = materialCategoryListApp.currentId;
        materialCategoryModalApp.display = true;
      } else if (!materialCategoryListApp.editModalForEdit && materialCategoryListApp.addModalForEdit) {//新增弹窗
        materialCategoryModalApp.display = true;
      } else {
        materialCategoryModalApp.title = "新增学生";
      }
      if (materialCategoryModalApp.id) findMaterialCategory(materialCategoryModalApp.id);
    })

    const findMaterialCategory = (id) => {
      MaterialCategoryService.findMaterialCategoryForView(id).then((res) => {
        materialCategoryModalApp.materialCategory = res.data;
        materialList.value=res.data.materials
        //TODO:为编辑准备.
        // materialCategoryModalApp.title = "编辑学生 " + materialCategoryModalApp.materialCategory.name;
      }).catch(error => {
        VXETable.modal.message({content: `查找学生出错，原因是：${error.message}`, status: 'error'});
      })
    }

    /*TODO:提交 新增&编辑*/
    const onSubmit = (data) => {
      // debugger;
      //当为数组时用逗号连接
      if (data.eid) {
        //修改
        MaterialCategoryService.updateMaterialCategory(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      } else {
        //新增
        // console.log(data)
        const $table = materialTable.value
        console.log($table.getInsertRecords())
        data.materials=$table.getInsertRecords()
        console.log(data)

        MaterialCategoryService.saveMaterialCategory(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          setTimeout(onBack, 1000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      }
    }

    /*TODO:继续提交*/
    /*const continueSubmit = () => {
      VXETable.modal.message({content: 'error 提示', status: 'error'});
    }*/

    /*TODO:返回列表*/
    const onBack = () => {
      materialCategoryListApp.editModalShowing = false;
      materialCategoryGrid.value.commitProxy("query");

    }

    //新增
    const insertEvent = async (row) => {
      console.log(row)
      /*this.materialEntityData = reactive({
        name: '',
        remark: ''
      })*/
      const $table = materialTable.value
      const {row: newRow} = await $table.insertAt(materialEntityData, row)
      await $table.setActiveCell(newRow, 'name')

      //新增数据无法动态添加进代理对象，
      // 需要之后获取对象时通过$table.getInsertRecords()获取所有新增后的对象
      console.log(materialList.value)

    }


    return {
      cityData,
      routeId,
      store,
      router,
      materialCategoryListApp,
      materialCategoryModalApp,
      materials,
      materialEntityData,
      materialTable,
      materialMap,
      materialList,
      tableConfig,
      onSubmit,
      // continueSubmit,
      onBack,
      insertEvent
    }

  },
})
</script>

<style scoped>

</style>
